package com.smedi.ismedi.inmail.core.port.adapter.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smedi.ismedi.database.starter.annotation.SkipSqlPermission;
import com.smedi.ismedi.inmail.core.domain.aggregatemodel.Criteria;
import com.smedi.ismedi.inmail.core.domain.aggregatemodel.TaskRecord;
import com.smedi.ismedi.inmail.core.domain.repository.TaskRecordRepository;
import com.smedi.ismedi.inmail.core.port.adapter.persistence.model.TaskRecordEntity;
import com.smedi.ismedi.inmail.core.port.adapter.persistence.mybatis.mapper.TaskRecordMapper;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Repository
@AllArgsConstructor
public class TaskRecordRepositoryImpl extends ServiceImpl<TaskRecordMapper, TaskRecordEntity> implements TaskRecordRepository, IService<TaskRecordEntity> {
    private final DozerUtil dozerUtil;

    @Override
    public List<TaskRecord> doListBySourceFromId(Long id) {
        QueryWrapper<TaskRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("source_from_id", id);
        return dozerUtil.convertor(list(queryWrapper), TaskRecord.class);
    }

    @Override
    public List<TaskRecord> doList(TaskRecord taskRecord) {
        TaskRecordEntity entity = dozerUtil.convertor(taskRecord, TaskRecordEntity.class);
        QueryWrapper<TaskRecordEntity> wrapper = new QueryWrapper<>(entity);
        wrapper.in("task_status", taskRecord.getOldStatus());
        return dozerUtil.convertor(list(wrapper), TaskRecord.class);
    }

    @Override
    public List<TaskRecord> doList(List<Long> ids) {
        return dozerUtil.convertor(listByIds(ids), TaskRecord.class);
    }

    @Override
    public List<TaskRecord> doListBySourceFromIdAndOldStatus(Long sourceFromId, String oldStatus) {
        QueryWrapper<TaskRecordEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("source_from_id", sourceFromId).eq("task_status", oldStatus);

        List<TaskRecordEntity> taskRecordEntityList = this.baseMapper.selectList(queryWrapper);

        if (!taskRecordEntityList.isEmpty()) {
            return dozerUtil.convertor(taskRecordEntityList, TaskRecord.class);
        } else {
            return null;
        }
    }


    @Override
    public List<TaskRecord> doInsertList(List<TaskRecord> taskRecords) {
        List<TaskRecordEntity> entities = dozerUtil.convertor(taskRecords, TaskRecordEntity.class);
        saveBatch(entities);
        return dozerUtil.convertor(entities, TaskRecord.class);
    }

    @Override
    public TaskRecord doInsert(TaskRecord taskRecord) {
        TaskRecordEntity entity = dozerUtil.convertor(taskRecord, TaskRecordEntity.class);
        save(entity);
        return dozerUtil.convertor(entity, TaskRecord.class);
    }

    @Override
    public TaskRecord doUpdate(TaskRecord taskRecord) {
        TaskRecordEntity entity = dozerUtil.convertor(taskRecord, TaskRecordEntity.class);
        updateById(entity);
        return dozerUtil.convertor(entity, TaskRecord.class);
    }

    @Override
    public TaskRecord doUpdateTaskDaily(TaskRecord taskRecord) {
        QueryWrapper<TaskRecordEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("source_from_id", taskRecord.getSourceFromId())
                .eq("project_id", taskRecord.getProjectId())
                .eq("project_name", taskRecord.getProjectName())
                .eq("task_name", taskRecord.getTaskName()).eq("task_type", taskRecord.getTaskType())
                .eq("task_describe", taskRecord.getTaskDescribe());
        TaskRecordEntity taskRecordEntity = this.baseMapper.selectOne(queryWrapper);
        taskRecordEntity.setTaskRead(true);
        taskRecordEntity.setTaskStatus("已完成");
        taskRecordEntity.setFinishTime(LocalDateTime.now());
        updateById(taskRecordEntity);
        return dozerUtil.convertor(taskRecordEntity, TaskRecord.class);
    }

    @Override
    public List<TaskRecord> doUpdateList(List<TaskRecord> taskRecords) {
        List<TaskRecordEntity> entities = dozerUtil.convertor(taskRecords, TaskRecordEntity.class);
        updateBatchById(entities);
        return dozerUtil.convertor(entities, TaskRecord.class);
    }

    @Override
    public Boolean doUpdateStatusByOldStatus(TaskRecord taskRecord) {
        TaskRecordEntity entity = dozerUtil.convertor(taskRecord, TaskRecordEntity.class);
        QueryWrapper<TaskRecordEntity> queryWrapper = new QueryWrapper<>();
        if (taskRecord.getSourceFromId() != null) {
            queryWrapper.eq("source_from_id", taskRecord.getSourceFromId());
        }
        if (taskRecord.getSponsorName() != null) {
            queryWrapper.eq("sponsor_name", taskRecord.getSponsorName());
        }
        if (taskRecord.getTaskType() != null) {
            queryWrapper.eq("task_type", taskRecord.getTaskType());
        }
        if (taskRecord.getTaskName() != null) {
            queryWrapper.eq("task_name", taskRecord.getTaskName());
        }
        if (taskRecord.getDealPersonId() != null) {
            queryWrapper.eq("deal_person_id", taskRecord.getDealPersonId());
            queryWrapper.eq("deal_person_name", taskRecord.getDealPersonName());
        }
        if (taskRecord.getId() != null) {
            queryWrapper.eq("id", taskRecord.getId());
        }
        queryWrapper.in("task_status", taskRecord.getOldStatus());
        update(entity, queryWrapper);
        return true;
    }

    @Override
    public Boolean doDeleteList(List<Long> ids) {
        return removeByIds(ids);
    }

    @Override
    public Boolean doDeleteBySourceIds(List<TaskRecord> taskRecords) {
        List<TaskRecordEntity> taskRecordEntities = new ArrayList<>();

        for (TaskRecord taskRecord : taskRecords) {
            LambdaQueryWrapper<TaskRecordEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TaskRecordEntity::getSourceFromId, taskRecord.getSourceFromId()).eq(TaskRecordEntity::getTaskType, taskRecord.getTaskType());
            List<TaskRecordEntity> taskRecordTemps = this.baseMapper.selectList(queryWrapper);
            if (!taskRecordTemps.isEmpty()) {
                taskRecordEntities.addAll(taskRecordTemps);
            }
        }

        if (taskRecordEntities.isEmpty()) {
            return true;
        }

        List<Long> ids = taskRecordEntities.stream().map(TaskRecordEntity::getId).collect(Collectors.toList());

        return this.doDeleteList(ids);
    }

    @Override
    @SkipSqlPermission
    public List<TaskRecord> doQueryTaskByTypeAndStatus(String taskName, String status) {
        QueryWrapper<TaskRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_name", taskName).eq("task_status", status);

        List<TaskRecordEntity> taskRecordEntityList = this.baseMapper.selectList(queryWrapper);

        if (!taskRecordEntityList.isEmpty()) {
            return dozerUtil.convertor(taskRecordEntityList, TaskRecord.class);
        } else {
            return null;
        }
    }

    @Override
    public List<TaskRecord> doQueryTask(Criteria criteria) {
        LambdaQueryWrapper<TaskRecordEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (criteria.getSponsorName() != null) {
            queryWrapper.eq(TaskRecordEntity::getSponsorName, criteria.getSponsorName());
        }
        if (criteria.getTaskType() != null) {
            queryWrapper.eq(TaskRecordEntity::getTaskType, criteria.getTaskType());
        }
        return null;
    }

    @Override
    public boolean deleteHistoryTask() {
        QueryWrapper<TaskRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sponsor_name", "系统默认");
        List<String> oldStatus = new ArrayList<>();
        oldStatus.add("进行中");
        oldStatus.add("已逾期");
        oldStatus.add("即将开始");
        queryWrapper.in("task_status", oldStatus);

        List<TaskRecordEntity> taskRecordEntities = this.baseMapper.selectList(queryWrapper);

        taskRecordEntities.stream().forEach(x -> x.setIsDeleted(true));
        updateBatchById(taskRecordEntities);

        return true;
    }

    @Override
    public boolean cancelTask(TaskRecord taskRecord) {
        LambdaQueryWrapper<TaskRecordEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaskRecordEntity ::getSourceFromId,taskRecord.getSourceFromId());
        queryWrapper.eq(TaskRecordEntity ::getProjectId,taskRecord.getProjectId());
        List<String> statusList = new ArrayList<>();
        statusList.add("已完成");
        statusList.add("已关闭");
        statusList.add("已删除");
        statusList.add("已撤销");
        queryWrapper.notIn(TaskRecordEntity ::getTaskStatus,statusList);
        List<TaskRecordEntity> list = this.baseMapper.selectList(queryWrapper);
        list.forEach(item->{
            item.setTaskStatus(taskRecord.getTaskStatus());
            this.baseMapper.updateById(item);
        });
        return true;
    }
}
